package com.xj.api.bussiness.wxLogin.common;

import com.alibaba.fastjson.JSONObject;
import com.xj.api.bussiness.wxPay.common.Configure;
import com.xj.common.bussiness.wxLogin.entity.WxAccessToken;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Configuration
@EnableScheduling
public class GetAccessToken {
    @Scheduled(fixedRate=1000*7150)
    public void accessToken() {
        String accessToken = "";
        BufferedReader in = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            URL realUrl = new URL(Configure.getAccessTokenUrl());
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            Map<String, List<String>> map = conn.getHeaderFields();
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            in = new BufferedReader(isr);
            String line;
            while ((line = in.readLine()) != null) {
                accessToken += line;
            }
        } catch (Exception e) {
            // 异常记录
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (Exception e2) {
                // 异常记录
            }
        }
        if (!accessToken.isEmpty()) {
            JSONObject object = JSONObject.parseObject(accessToken);
            if (object.get("access_token") != null && object.get("expires_in") != null) {
                String access_token = object.get("access_token").toString();
                Integer expires_in = new Integer(object.get("expires_in").toString());
                WxAccessToken.getWxAccessToken().setExpires_in(expires_in);
                WxAccessToken.getWxAccessToken().setAccess_token(access_token);
                System.out.println("定时"+new Date()+"刷新的access_token→→→→→》》》→→→→→"+WxAccessToken.getWxAccessToken().getAccess_token());
            }
        }
    }
}
